//
//  XYComposePictureView.swift
//  WeiboSourceCode
//
//  Created by 周星宇 on 16/1/5.
//  Copyright © 2016年 cn.weibo. All rights reserved.
//

import UIKit
import SVProgressHUD
private let composePictureViewCellId = "composePictureViewCellId"
private let composeViewControllerMargin:CGFloat = 8

// 定义cell 的代理协议
protocol ComposePictureViewCellProtocol: NSObjectProtocol {
    
    func cellDidClickDeleteBtnWith(index:NSIndexPath)
}
class XYComposePictureView: UICollectionView {
    
    var didClickAddClosure: (() -> ())?
    // 数据源数组
    lazy var images: [UIImage] = [UIImage]()
    
    override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
        super.init(frame: frame, collectionViewLayout: UICollectionViewFlowLayout())
        setUpUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    private func setUpUI() {
        dataSource = self
        delegate = self
        registerClass(XYComposePictureViewCell.self, forCellWithReuseIdentifier: composePictureViewCellId)
        // 设置cell 大小
        let itemMargin: CGFloat = 5
        let itemWH = (kSCREENWITH - 2 * itemMargin - 2 * composeViewControllerMargin) / 3
        let layout = collectionViewLayout as! UICollectionViewFlowLayout
        layout.itemSize = CGSizeMake(itemWH, itemWH)
        layout.minimumLineSpacing = itemMargin
        layout.minimumInteritemSpacing = itemMargin
    }
    // 给外界提供的接口
    func addImage(image: UIImage) {
        
        // 判断图片数量超过9张直接返回
        if images.count == 9 {
            SVProgressHUD.showInfoWithStatus("图片数量太多了")
            return
        }
        hidden = false
        images.append(image)
        reloadData()
    }
}
extension XYComposePictureView: ComposePictureViewCellProtocol {
    
    func cellDidClickDeleteBtnWith(index: NSIndexPath) {
        
        self.images.removeAtIndex(index.item)
        reloadData()
        if images.count == 0 {
            hidden = true
        }
    }
}
extension XYComposePictureView: UICollectionViewDelegate,UICollectionViewDataSource {
    // 让collectionView取消选中某一行
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        collectionView.deselectItemAtIndexPath(indexPath, animated: true)
        // 判断选择的是否是加号按钮
        if indexPath.item == images.count { // 说明是加号按钮
            // 执行闭包 通知控制器
            didClickAddClosure?()
        }
    }
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        return (images.count == 0 || images.count == 9) ? images.count : images.count + 1
    }
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(composePictureViewCellId, forIndexPath: indexPath) as! XYComposePictureViewCell
        
        if indexPath.item == images.count { // 说明当前cell 是最后一个 显示加号
            cell.image = nil
        }else {
            cell.indexPath = indexPath
            let image = images[indexPath.item]
            cell.image = image
        }
        cell.delegate = self
        return cell
    }
}
class XYComposePictureViewCell: UICollectionViewCell {
    
    weak var delegate: ComposePictureViewCellProtocol?
    // 记录cell的indexPath
    var indexPath: NSIndexPath?
    var image: UIImage? {
        
        didSet {
            if image == nil {
                // 说明是按钮
                imageView.image = UIImage(named: "compose_pic_add")
                imageView.highlightedImage = UIImage(named: "compose_pic_add_highlighted")
                // 隐藏删除按钮
                deleBtn.hidden = true
            }else {
                imageView.image = image
                imageView.highlightedImage = nil
                deleBtn.hidden = false
            }
        }
    }
    override init(frame: CGRect) {
        super.init(frame: frame)
        contentView.addSubview(imageView)
        contentView.addSubview(deleBtn)
        // 添加约束
        imageView.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(contentView)
        }
        deleBtn.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(imageView)
            make.trailing.equalTo(imageView)
        }
    }
    // MARK: 懒加载控件
    private lazy var imageView: UIImageView = UIImageView()
    private  lazy var deleBtn: UIButton = {
        let btn = UIButton()
        btn.setImage(UIImage(named: "compose_photo_close"), forState: UIControlState.Normal)
        btn.addTarget(self, action: "didClickDeleteBtn:", forControlEvents: .TouchUpInside)
        return btn
    }()
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    @objc private func didClickDeleteBtn(btn:UIButton) {
        
        delegate?.cellDidClickDeleteBtnWith(indexPath!)
    }
    
    
}